<?php
/**
 * Created by PhpStorm.
 * User: s.utkin
 * Date: 18.05.2015
 * Time: 17:40
 */

namespace SitemapGenerator;


use Pinenut\Model2\Finder;

class FinderIterator implements \Iterator{

	/**
	 * @var Finder
	 */
	protected $finder = null;
	protected $returnedField = null;
	protected $count = null;
	protected $steps = null;
	protected $step = null;
	protected $itemsPerStep = null;

	protected $buffer = [];
	protected $bufferIndex = 0;

	public function __construct(Finder $finder, $returnedField = null, $itemsPerStep = 1000)
	{
		$this->finder = $finder;
		$this->returnedField = $returnedField;
		$this->itemsPerStep = $itemsPerStep;
		$this->count = $finder->count();
		$this->steps = ceil($this->count / $this->itemsPerStep);
		$this->step = 0;

		if ($this->returnedField != null) {
			$this->finder->fields([$this->returnedField]);
		}
	}

	/**
	 * (PHP 5 &gt;= 5.0.0)<br/>
	 * Return the current element
	 * @link http://php.net/manual/en/iterator.current.php
	 * @return mixed Can return any type.
	 */
	public function current()
	{
		return $this->buffer[$this->bufferIndex]->{$this->returnedField};
	}

	/**
	 * (PHP 5 &gt;= 5.0.0)<br/>
	 * Move forward to next element
	 * @link http://php.net/manual/en/iterator.next.php
	 * @return void Any returned value is ignored.
	 */
	public function next()
	{
		$this->bufferIndex++;

		if ($this->bufferIndex >= $this->itemsPerStep) {
			$this->step++;
			$this->loadStep();
		}
	}

	public function key()
	{
		return $this->step * $this->itemsPerStep + $this->bufferIndex;
	}


	public function valid()
	{
		return count($this->buffer) && isset($this->buffer[$this->bufferIndex]);
	}

	public function rewind()
	{
		$this->step = 0;
		$this->loadStep($this->step);
	}

	protected function loadStep()
	{
		$this->bufferIndex = 0;
		$this->buffer = $this->finder
			->offset($this->step * $this->itemsPerStep)
			->limit($this->itemsPerStep)
			->all();
	}
}